#pragma once
#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#define LISTEN_QUEUE 20 
class Sock
{
public:
    Sock(uint16_t port = 8080, std::string ip = "0.0.0.0")
        :_port(port)
        ,_ip(ip)
    {
    }
    int CreatSock()
    {
        _sock = socket(AF_INET, SOCK_STREAM, 0);
        if(_sock < 0)
        {
            std::cout << "socket fail:" << strerror(errno) << errno << std::endl;
            exit(1);
        }
        return _sock;
    }
    void Bind()
    {
        sockaddr_in server;
        server.sin_family = AF_INET;
        server.sin_port = htons(_port);
        server.sin_addr.s_addr = inet_addr(_ip.c_str());
        int ret = bind(_sock, (sockaddr*)(&server), sizeof(server));
        if(ret < 0)
        {
            std::cout << "bind fail:" << strerror(errno) << errno << std::endl;
            exit(2);
        }
    }
    void Listen()
    {
        int ret = listen(_sock, LISTEN_QUEUE);
        if(ret < 0)
        {
            std::cout << "Listen fail:" << strerror(errno) << errno << std::endl;
            exit(3);
        }
    }
    void Connect(int sock, std::string ip, uint16_t port)
    {
        sockaddr_in server;
        server.sin_addr.s_addr = inet_addr(ip.c_str());
        server.sin_family = AF_INET;
        server.sin_port = htons(port);
        int ret = connect(sock, (sockaddr *)(&server), sizeof(server));
        if(ret < 0)
        {
            std::cout << "connect fail:" << strerror(errno) << errno << std::endl;
            exit(4);
        }
    }
    int Accept()
    {
        sockaddr_in client;
        socklen_t len = sizeof(client);
        int sock = accept(_sock, (sockaddr *)(&client), &len);
        if(sock < 0)
        {
            std::cout << "accept fail:" << strerror(errno) << errno << std::endl;
            exit(5);
        }
        return sock;
    }
    ~Sock()
    {
        if(_sock > 0)
            close(_sock);
    }
private:
    int _sock;
    uint16_t _port;
    std::string _ip;
};